Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

draft: hiding filters showing no results (not working) #1403

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mbacherycz
Copy link
Contributor

@mbacherycz mbacherycz commented Nov 27, 2024

Hva er endret?

Related Issue(s)

  • #{issue number}

Dokumentasjon / Storybook / testdekning

  • Dokumentasjon er oppdatert eller ikke relevant / nødvendig.
  • Ny komponent har en eller flere stories i Storybook, eller så er ikke dette relevant.
  • Det er blitt lagt til nye tester / eksiterende tester er blitt utvidet, eller tester er ikke relevant.

Skjermbilder eller GIFs (valgfritt)

Summary by CodeRabbit

  • New Features

    • Improved filtering mechanism in the Inbox component, allowing for a more refined display of dialogs based on active filters.
    • Enhanced filter bar settings to reflect only relevant options from filtered dialogs.
  • Bug Fixes

    • Adjusted logic for generating filter options to ensure accuracy based on the currently filtered dialogs.

@mbacherycz mbacherycz requested a review from a team as a code owner November 27, 2024 14:53
@mbacherycz mbacherycz self-assigned this Nov 27, 2024
Copy link

coderabbitai bot commented Nov 27, 2024

📝 Walkthrough

Walkthrough

The pull request introduces modifications to the Inbox component and the getFilterBarSettings function to enhance the filtering logic. A new memoized variable, filteredDialogs, is added to the Inbox component to store filtered results based on active filters. The getFilterBarSettings function is updated to accept this new variable, ensuring that filter options reflect only the dialogs that remain after filtering. These changes improve the accuracy and efficiency of how dialogs and filter settings are processed.

Changes

File Path Change Summary
packages/frontend/src/pages/Inbox/Inbox.tsx Added filteredDialogs variable for improved filtering; updated filter settings logic to use filteredDialogs.
packages/frontend/src/pages/Inbox/filters.ts Updated getFilterBarSettings function to include filteredDialogs parameter; modified logic to generate filter options based on filteredDialogs.

Possibly related PRs

Suggested reviewers

  • seanes: Suggested for review based on expertise in the relevant components.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
packages/frontend/src/pages/Inbox/filters.ts (1)

Line range hint 77-155: Consider implementing proper filter dependencies

The current approach of using filteredDialogs to hide empty filters might not be the most maintainable solution. Consider implementing proper filter dependencies where:

  1. Each filter's options are dynamically updated based on other active filters
  2. The filtering logic is applied incrementally
  3. The UI clearly shows which filters are dependent on others

This would provide a better user experience and make the code more maintainable.

Would you like me to provide an example implementation of this approach?

packages/frontend/src/pages/Inbox/Inbox.tsx (1)

109-111: Remove commented out code

Dead code should be removed rather than left commented out. If this code needs to be referenced later, it can be found in the git history.

- // const filterBarSettings = useMemo(() => {
- //   return getFilterBarSettings(dataSource, filteredDialogs, format);
- // }, [dataSource, filteredDialogs]);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2cbf387 and a93a009.

📒 Files selected for processing (2)
  • packages/frontend/src/pages/Inbox/Inbox.tsx (1 hunks)
  • packages/frontend/src/pages/Inbox/filters.ts (5 hunks)
🔇 Additional comments (3)
packages/frontend/src/pages/Inbox/filters.ts (2)

151-152: LGTM! This is the correct approach

This section correctly uses filteredDialogs for generating date options, which should be replicated in other filter sections.


92-96: ⚠️ Potential issue

Fix inconsistent sender counts

The counts are calculated from the original dialogs array while options are generated from filteredDialogs. This means the counts won't reflect the actual available options after filtering, which could mislead users.

-const senders = dialogs.map((p) => p.sender.name);
+const senders = filteredDialogs.map((p) => p.sender.name);
 const senderCounts = countOccurrences(senders);

 const validSenders = filteredDialogs.map((p) => p.sender.name);
 const uniqueSenders = Array.from(new Set(validSenders));

Likely invalid or redundant comment.

packages/frontend/src/pages/Inbox/Inbox.tsx (1)

113-117: ⚠️ Potential issue

Fix dependency array and implementation issues in filterBarSettings

There are several issues with this implementation:

  1. The dependency array is missing filteredDialogs, which could lead to stale filter options

  2. The current implementation filters out options with length ≤ 1, but this doesn't match the PR objective of "hiding filters showing no results"

  3. The implementation might hide valid single-option filters that users still need to see

  4. Fix the dependency array:

  const filterBarSettings = useMemo(
    () => getFilterBarSettings(dataSource, filteredDialogs, format).filter((setting) => setting.options.length > 1),
-   [dataSource, format],
+   [dataSource, filteredDialogs, format],
  );
  1. Consider revising the implementation to align with the PR objective:
  const filterBarSettings = useMemo(
-   () => getFilterBarSettings(dataSource, filteredDialogs, format).filter((setting) => setting.options.length > 1),
+   () => {
+     const settings = getFilterBarSettings(dataSource, filteredDialogs, format);
+     return settings.filter((setting) => {
+       // Only hide filters that would yield no results when applied
+       const hasMatchingDialogs = filteredDialogs.some(dialog => 
+         setting.options.some(option => 
+           dialog[setting.key] === option.value
+         )
+       );
+       return hasMatchingDialogs;
+     });
+   },
    [dataSource, filteredDialogs, format],
  );

Let's verify the filter behavior:

Comment on lines +112 to +116

const validReceivers = filteredDialogs.map((p) => p.receiver.name);
const uniqueReceivers = Array.from(new Set(validReceivers));

return uniqueReceivers.map((receiver) => ({
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Fix inconsistent receiver counts and reduce code duplication

  1. The counts are calculated from the original dialogs array, causing the same inconsistency issue as the sender filter.
  2. The logic for generating options is duplicated between sender and receiver filters.

First, fix the counting:

-const receivers = dialogs.map((p) => p.receiver.name);
+const receivers = filteredDialogs.map((p) => p.receiver.name);
 const receiversCount = countOccurrences(receivers);

Then, consider extracting a helper function to reduce duplication:

const getParticipantOptions = (
  dialogs: InboxItemInput[],
  participantType: 'sender' | 'receiver',
  labelPrefix: string
) => {
  const participants = dialogs.map((p) => p[participantType].name);
  const counts = countOccurrences(participants);
  const unique = Array.from(new Set(participants));
  
  return unique.map((name) => ({
    displayLabel: `${t(labelPrefix)} ${name}`,
    value: name,
    count: counts[name],
  }));
};

Comment on lines +77 to +81
export const getFilterBarSettings = (
dialogs: InboxItemInput[],
filteredDialogs: InboxItemInput[],
format: FormatFunction,
): FilterSetting[] => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Consider using only filteredDialogs for consistency

The function now takes both dialogs and filteredDialogs, but this creates potential inconsistencies in the counts vs. available options. Consider using only filteredDialogs for both counting and option generation to ensure consistency.

 export const getFilterBarSettings = (
-  dialogs: InboxItemInput[],
   filteredDialogs: InboxItemInput[],
   format: FormatFunction,
 ): FilterSetting[] => {

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +131 to +140
const statuses = dialogs.map((p) => p.status);
const statusCounts = countOccurrences(statuses);

const validStatuses = filteredDialogs.map((p) => p.status);
const uniqueStatuses = Array.from(new Set(validStatuses));

return uniqueStatuses.map((statusLabel) => ({
displayLabel: t(`status.${statusLabel.toLowerCase()}`),
value: statusLabel,
count: statusCount[statusLabel],
count: statusCounts[statusLabel],
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

Based on the results from our verification attempts, I can generate the final response:

Fix status counts and verify translation key case handling

The status counts issue needs to be fixed as proposed in the diff, but regarding the translation keys, we found evidence in the translation files (nb.json and en.json) that the lowercase status keys are correct. The translation files contain entries like "status.completed", "status.draft", etc., which match the lowercase transformation in the code.

  • Fix the counting inconsistency by using filteredDialogs instead of dialogs
  • ✓ Translation key case handling is correct as-is
🔗 Analysis chain

Fix status counts and verify translation key case handling

  1. The status counts have the same inconsistency issue as other filters.
  2. The translation key uses lowercase which might not match the actual translation keys.
-const statuses = dialogs.map((p) => p.status);
+const statuses = filteredDialogs.map((p) => p.status);
 const statusCounts = countOccurrences(statuses);

Let's verify the translation keys:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if translation keys exist in lowercase
rg -l "status\.: \{" . | xargs rg "status\.[A-Z]+" -A 1

Length of output: 57


Script:

#!/bin/bash
# Let's try a different approach to find translation files and keys
fd -e json -e yaml -e yml | xargs rg "status\." -B 1 -A 1

# Also search for translation related files
fd "i18n|translation|locale" --type f

# Look for actual status values in the code
rg "status: ['\"](.*?)['\"]" --type ts

Length of output: 4105


Script:

#!/bin/bash
# Let's find the actual status values used in the dialogs
rg "status: ['\"]" packages/frontend/src/pages/Inbox -B 2 -A 2

# Also check how these status values are used in the code
ast-grep --pattern 'status.$_'

Length of output: 99


Script:

#!/bin/bash
# Let's try to find the Dialog type definition to see status values
rg "type.*Dialog.*status" --type ts -A 5

# And check for enum definitions related to status
rg "enum.*Status" --type ts -A 10

# Also look for actual status assignments in the Inbox directory
rg "\.status\s*(=|:)" packages/frontend/src/pages/Inbox

Length of output: 136

Comment on lines +105 to +108
const filteredDialogs = useMemo(() => {
return filterDialogs(dataSource, activeFilters, format);
}, [dataSource, activeFilters]);

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove duplicate memoized variable

The filteredDialogs variable duplicates the exact same logic as itemsToDisplay defined above. This creates unnecessary memory overhead and complexity.

Remove this duplicate and use the existing itemsToDisplay variable instead:

- const filteredDialogs = useMemo(() => {
-   return filterDialogs(dataSource, activeFilters, format);
- }, [dataSource, activeFilters]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant